<?php
class Db{
	private static $conn="";//数据库连接资源
	//连接数据库（静态）
	static function instance($ip,$user,$pw,$dbName,$char="utf8"){
		$conn=mysql_connect($ip,$user,$pw);
		db::$conn=$conn;
		//选择数据库
		mysql_select_db($dbName);
		//设计交互字符集
		mysql_query("set names {$char}");
		if(is_resource($conn)){
			return true;//连接成功返回true
		}
		return false;
	}
	//增加记录
	/*
	 * tableName:指定表名
	 * arr:传一个关联下标数组，下标为字段名，其值为这个字段写入的内容
	 *     例如 $arr=array('title'=>'title1','content'=>'content1')
	 */
	static function insert($tableName,$arr){
		//根据数组，产生字段列表，值列表
		$columList="";
		$valueList="";
		foreach($arr as $key=>$value){
			$columList.=",".$key;
			$valueList.=",'".$value."'";
		}
		$columList=substr($columList,1);
		$valueList=substr($valueList,1);
		//拼insert语句
		$sql="insert into {$tableName}({$columList}) values({$valueList})";
		//echo "insert->".$sql."<br/>";
		//exit();
		$re=mysql_query($sql);
		if($re==true){
			return mysql_insert_id();
		}else{
			return false; 
		}
	}
	//删除
	//$arr=array("主键字段名"=>id值)
	static function delete($tableName,$arr){
		foreach($arr as $key=>$value){
			$sql="delete from {$tableName} where {$key}={$value}";
		}
		echo "delete->".$sql."<br>";
		return mysql_query($sql);
	}
	//删除多个  但是你需要提供一个由主键组成的数组作为参数传给它
	static function deleteMoreByKey($tableName,$keyArr,$keyName){
		if($keyArr == ""){
			return false;
		}
		$where="";
		foreach ($keyArr as $value){
			$where .=",".$value;
		}
		$whereStr = substr($where, 1);
		$where = " where {$keyName} in (".$whereStr.")";
		$sql = "delete from {$tableName} {$where}";
		//echo $sql;
		return mysql_query($sql);
	}
	//修改
	//$arr=array('title'=>'title1','content'=>'content1','nid'=>5)
	//主键字段名 update 表名 set title='title1',content='content' where nid=5
	//primaryColumName:主键字段名称
	//tableName:表名
	static function update($tableName,$arr,$primaryColumName){
		//产生where子句  update 表名 set title='title1',content='content' where nid=5
		$where="where {$primaryColumName}=".$arr[$primaryColumName];
		unset($arr[$primaryColumName]);
		$columValueList="";//title='title1',content='content1'
		foreach($arr as $key=>$value){
			$columValueList.=",".$key."='".$value."'";	
		}
		$columValueList=substr($columValueList,1);
		//update语句
		$sql="update {$tableName} set {$columValueList} {$where}";
		//echo $sql;
		return mysql_query($sql);
	}
	//查询
	//$tableName,$columList,$where="",$limit=""$group="",$order="",
	//news * where type=1 limit 0,3
	static function select($tableName,$columList,$where="",$limit="",$order="",$group=""){
		$sql="select {$columList} from {$tableName} {$where} {$group} {$order} {$limit}";
		//echo "select->".$sql."<br>";
		//exit();
		$result=mysql_query($sql);//结果集资源变量
		if(is_resource($result)){
				$arr=array();
				while($re=mysql_fetch_assoc($result)){
					$arr[]=$re;
				}
				return $arr;
		}else{
			return false;
		}
	}
	static function close(){
		mysql_close(self::$conn);
	}
	static function query($sql){
		return mysql_query($sql);
	}
	
}










